package com.iclippi.client;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;

public class MessagePanel extends Composite {

	private static MessagePanel singlton = new MessagePanel();

	private PopupPanel popupPanel = new PopupPanel();

	private MessagePanel() {
		popupPanel.setStylePrimaryName("messagePopup");

	}

	private class CloseTimer extends Timer {

		@Override
		public void run() {
			popupPanel.hide();
		}
	}

	private CloseTimer closeTimer = new CloseTimer();
	
	public static final int DEFAULT_TIMEOUT = 3000;

	/**
	 * Get an instance of the MessagePanel
	 * @return
	 */
	public static MessagePanel getInstance() {
		return singlton;
	}

	/**
	 * Show message in the upper-left corner of the screen. Remove it after the
	 * default timeout expires.
	 * 
	 * @param message
	 */
	public void showMessage(String message) {
		showMessage(new HTML(message), MessagePanel.DEFAULT_TIMEOUT);
	}

	/**
	 * Show message in the upper-left corner of the screen. Remove it after the
	 * timeout expires. Set timeout 0 to manually remove it, or to remove it by
	 * another message.
	 * 
	 * @param message
	 */
	public void showMessage(String message, int timeout) {
		showMessage(new HTML(message), timeout);
	}

	/**
	 * Show a message widget in the upper-left corner of the screen. Remove it
	 * after the default timeout expires.
	 * 
	 * @param message
	 */
	public void showMessage(Widget widget) {
		showMessage(widget, MessagePanel.DEFAULT_TIMEOUT);
	}

	/**
	 * Show a message widget in the upper-left corner of the screen. Remove it
	 * after the timeout expires. Set timeout 0 to manually remove it, or to
	 * remove it by another message.
	 * 
	 * @param message
	 */
	public void showMessage(Widget widget, int timeout) {
		closeTimer.cancel();
		popupPanel.clear();
		popupPanel.add(widget);
		popupPanel.setPopupPositionAndShow(new PositionCallback() {

			@Override
			public void setPosition(int offsetWidth, int offsetHeight) {
				adjustSize();

			}
		});
		popupPanel.show();
		
		if (timeout>0) closeTimer.schedule(timeout);
	}
	
	public void hideMessage(){
		popupPanel.hide();  
	}
	
	public void adjustSize(){
		popupPanel.setPopupPosition(Window.getClientWidth()
				- popupPanel.getOffsetWidth() - 8, 0);
	}

}
